import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/commons/log.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/data/models/settings_model.dart';
import 'package:flutter_provider_demo/data/models/user.dart';
import 'package:flutter_provider_demo/data/repositories/auth_repository.dart';
import 'package:flutter_provider_demo/data/repositories/settings_repository.dart';

class ProfileViewModel extends ChangeNotifier {
  ProfileViewModel({
    required AuthRepository authRepository,
    required SettingsRepository settingsRepository,
  })  : _authRepository = authRepository,
        _settingsRepository = settingsRepository {
    _loadUser();
    _loadSettings();
  }

  final _log = Log();
  final AuthRepository _authRepository;
  final SettingsRepository _settingsRepository;

  UserModel? _user;
  UserModel? get user => _user;

  late SettingsModel _settingsModel;
  SettingsModel get settingsModel => _settingsModel;

  void _loadUser() async {
    final r = await _authRepository.getUser();
    if (r is Ok) {
      _user = (r as Ok).value;
      notifyListeners();
    } else {
      _log.error('Load user error: ${(r as Error).errorMessage()}');
    }
  }

  void _loadSettings() async {
    _settingsModel = _settingsRepository.settingsModel;
    notifyListeners();
  }

  void logout() {
    _user = null;
    notifyListeners();
  }

  List<String> languages = [
    'en',
    'zh',
  ];

  void changeLanguage(String? language) async {
    if (language == null) {
      return;
    }
    await _settingsRepository.setLanguage(language);

    _loadSettings();
  }

  void changeDarkMode(bool value) async {
    await _settingsRepository.updateDarkMode(value);
    _loadSettings();
  }
}
